package com.jw.xzg.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jw.xzg.R;
import com.jw.xzg.adapter.DealAdapter;
import com.jw.xzg.adapter.FriendAdapter;
import com.jw.xzg.callback.JsonCallback;
import com.jw.xzg.model.ActiveModel;
import com.jw.xzg.model.BottleModel;
import com.jw.xzg.model.BusinessModel;
import com.jw.xzg.model.DealItem;
import com.jw.xzg.model.DealListModel;
import com.jw.xzg.model.FriendItem;
import com.jw.xzg.model.FriendListModel;
import com.jw.xzg.model.FriendModel;
import com.jw.xzg.model.FriendSearchModel;
import com.jw.xzg.model.IncomeModel;
import com.jw.xzg.model.IncrementModel;
import com.jw.xzg.model.NewsListModel;
import com.jw.xzg.model.ReportItem;
import com.jw.xzg.model.SmsModel;
import com.jw.xzg.model.UserModel;
import com.jw.xzg.service.MusicService;
import com.jw.xzg.utils.CommonUtils;
import com.jw.xzg.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.zhy.http.okhttp.OkHttpUtils.post;

public class MainActivity extends AppCompatActivity {
    final static String BOTTLE_URL = "http://61.164.158.234:8080/angelFor/userbuild?depot";
    final static String INCOME_URL = "http://61.164.158.234:8080/angelFor/userbuild?checkMoney";
    final static String USER_URL = "http://61.164.158.234:8080/angelFor/user?getNick";
    final static String Friend_URL = "http://61.164.158.234:8080/angelFor/user?friend";//邀请朋友
    final static String BUILD_URL = "http://61.164.158.234:8080/angelFor/userbuild?payHouse";
    final static String Friend_LIST_URL = "http://61.164.158.234:8080/angelFor/user?getfather";//我的朋友列表
    final static String Friend_SEARCH_URL = "http://61.164.158.234:8080/angelFor/user?find";//查找朋友
    final static String Friend_ACTIVE_URL = "http://61.164.158.234:8080/angelFor/usermoney?active";//激活朋友
    final static String INCREMENT_URL = "http://61.164.158.234:8080/angelFor/userbuild?income";//激活朋友
    final static String BUSINESS_URL = "http://61.164.158.234:8080/angelFor/userbuild?operate";//
    final static String TRANS_URL = "http://61.164.158.234:8080/angelFor/transaction?findTransaction";
    final static String  NEWS_URL = "http://61.164.158.234:8080/angelFor/report?sys";
    final static String SMS_URL = "http://61.164.158.234:8080/angelFor/user?sendMessage";
    final static String SEND_TRANS_URL = "http://61.164.158.234:8080/angelFor/transaction?sendTransaction";
    final static String CHANGE_PASSWORD_URL= "http://61.164.158.234:8080/angelFor/user?forget";
    final static String AGREE_URL = "http://61.164.158.234:8080/angelFor/transaction?accptTransaction"; //reciver
    final static String REFUSE_URL = "http://61.164.158.234:8080/angelFor/transaction?canTransaction";
    final static String FINFISH_URL = "http://61.164.158.234:8080/angelFor/transaction?bingoTransaction";
    final static String HOUSE_URL = "http://61.164.158.234:8080/angelFor/userbuild?payHouse";

    public static MainActivity _this ;

    Double[][] build_flag_position = { //x,y坐标
            {0.603,0.0627},
            {0.593,0.947},
            {0.850,0.926},
            {0.692,0.374},
            {0.860,0.219},
            {0.164,0.835},
            {0.023,0.924},
            {0.318,0.550},
            {0.693,0.374},
            {0.174,0.169},
            {0.887,0.533},
            {0.503,0.333},
            {0.098,0.482}


    };






    Integer friendListPageNum = 1; //第几页
    Integer friendListPageSize = 4;//每页几条
    Integer friendListTotal = 0;//总数

    Integer transListPageNum = 1; //第几页
    Integer transListPageSize = 6;//每页几条
    Integer transListTotal = 0;//总数





    int currentVolume;

    private List<Map<String, Object>> data_list ;
    GridView gview;
    Integer build_tab = 1;
    Integer build_tab_selected_item = null;
    SimpleAdapter sim_adapter;
    private Dialog loginDialog;
    private Dialog startDialog;
    private Dialog bottleDialog;//仓库
    private Dialog incomeDialog;
    private Dialog inviteDialog;
    private Dialog messageDialog;
    private Dialog friendDialog;
    private Dialog friendActiveDialog;
    private Dialog incrementDialog;
    private Dialog dealDialog;
    private Dialog dealSearchDialog;
    private Dialog dealCodeDialog;
    private Dialog settingDialog;
    private Dialog changePasswordDialog;
    private Dialog buildDialog;

    //adapter
    private FriendAdapter friendAdapter;
    private DealAdapter dealAdapter;

    //指定交易用户
    private FriendSearchModel dealUser;

    Intent musicService;
    private SoundPool mSound;
    private int soundId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        startAnimation();
        startCloudAnimation();

        musicService = new Intent(this, MusicService.class);
        startService(musicService);
        //onLoginClick();
        //onStartClick();
        initView();
        _this = this;
    }
    /*
    * 初始化用户数据
    * */
    public void initView(){
        UserModel user = CommonUtils.getCurrentUser();
       TextView username =  (TextView)findViewById(R.id.user_username);
        username.setText(user.getNickName());
        TextView asset =  (TextView)findViewById(R.id.user_asset);
        asset.setText(user.getAsset());

        TextView day =  (TextView)findViewById(R.id.user_day);
        day.setText(user.getDay());

        //初始化建筑物
        initBuild();
        intBuildSound();



    }

     public void initBuild(){
         RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.activity_main);
         DisplayMetrics metric = new DisplayMetrics();
         getWindowManager().getDefaultDisplay().getMetrics(metric);
         int width = metric.widthPixels;     // 屏幕宽度（像素）
         int height = metric.heightPixels;

         UserModel user = CommonUtils.getCurrentUser();
         Integer [] build = new Gson().fromJson(user.getSrc(), Integer[].class);
         Double _build_flag_position[][] = build_flag_position.clone();

        for(int i=0;i<build.length;i++){
            _build_flag_position[build[i]-1][0] = null;
            _build_flag_position[build[i]-1][1] = null;

        }
         RelativeLayout.LayoutParams layoutParams;
        // layoutParams =   new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

         for(int j=0;j<_build_flag_position.length;j++){
             if(_build_flag_position[j][0]!=null){
             layoutParams =   new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

             ImageView flag = new ImageView(this);
                 flag.setBackgroundResource(R.drawable.build_flag);
                 layoutParams.leftMargin = (int) (width * _build_flag_position[j][0]); // 0.18
                 layoutParams.topMargin = (int) (height * _build_flag_position[j][1]);
                 flag.setLayoutParams(layoutParams);
                 mainLayout.addView(flag,0);
             }
         }

    }
    public void addBuild(int position){
        RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.activity_main);
        RelativeLayout.LayoutParams layoutParams;
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int height = metric.heightPixels;

        layoutParams =   new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        ImageView flag = new ImageView(this);
        flag.setBackgroundResource(R.drawable.build_flag);
        layoutParams.leftMargin = (int) (width * build_flag_position[position-1][0]); // 0.18
        layoutParams.topMargin = (int) (height * build_flag_position[position-1][1]);
        flag.setLayoutParams(layoutParams);
        mainLayout.addView(flag,0);
    }


    public void onBottleClose(View view){
        bottleDialog.hide();
    }

    public void onBottleClick(View view){
        if(bottleDialog==null){
            bottleDialog =  new Dialog(MainActivity.this);
            bottleDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            bottleDialog.setContentView(R.layout.dialog_bottle);
              // dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            bottleDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            bottleDialog.setCancelable(false);



        }
        //加载网络数据
        post()
                .url(BOTTLE_URL)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<BottleModel>(BottleModel.class) {
                    @Override
                    public void onResponse(final BottleModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                            return;
                        }
                        //显示对话框
                        getUserInfo(CommonUtils.getToken());
                        ((TextView)bottleDialog.findViewById(R.id.bottle_amount)).setText(response.getMessage());

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });

        bottleDialog.show();


    }
    public void onIncomeClose(View view){
        incomeDialog.dismiss();
        incomeDialog = null;
    }

    /*
    * 收银
    * */
    public void onIncomeClick(View view){
        if(incomeDialog==null){
            incomeDialog =  new Dialog(MainActivity.this);
            incomeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            incomeDialog.setContentView(R.layout.dialog_income);
            // dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            incomeDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            incomeDialog.setCancelable(false);
            //加载网络数据
            post()
                    .url(INCOME_URL)
                    .addParams("token", CommonUtils.getToken())
                    .build()
                    .execute(new JsonCallback<IncomeModel>(IncomeModel.class) {
                        @Override
                        public void onResponse(final IncomeModel response,int id) {
                            if (response == null) {
                                ToastUtils.show(MainActivity.this,"数据错误");
                                return;
                            }else if(!response.isSuccess()){
                                ToastUtils.show(MainActivity.this,response.getMessage());
                                return;
                            }
                            //显示对话框
                            getUserInfo(CommonUtils.getToken());
                            ((TextView)incomeDialog.findViewById(R.id.income_txt)).setText(response.getMessage());

                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e("error",e.toString());
                            ToastUtils.show(MainActivity.this,"网络错误");
                            return;
                        }
                    });

            incomeDialog.show();
        }else{
            incomeDialog.show();
        }

    }


    public void getUserInfo(final String token){
        post()
                .url(USER_URL)
                .addParams("token", token)
                .build()
                .execute(new JsonCallback<UserModel>(UserModel.class) {
                    @Override
                    public void onResponse(final UserModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                            return;
                        }

                        CommonUtils.setCurrentUser(response);
                        Log.e("userinfo","asset:"+response.getAsset());
                        //保存用户信息
                        //getUserInfo(response.getToken());
                        initView();

                    }

                    @Override
                    public void onError(Call call, Exception e,int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });
    }


    public void onInviteClick(View view){
        if(incomeDialog==null){
            inviteDialog =  new Dialog(MainActivity.this);
            inviteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            inviteDialog.setContentView(R.layout.dialog_invite);
            // inviteDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            inviteDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            inviteDialog.setCancelable(false);
            inviteDialog.show();
        }
        inviteDialog.show();


    }

    public void inviteFriend(View view){
       TextView inviteName = (TextView)inviteDialog.findViewById(R.id.invite_name);
        String invite_name = inviteName.getText().toString();
        TextView invitePhone = (TextView)inviteDialog.findViewById(R.id.invite_phone);
        String invite_phone = invitePhone.getText().toString();
        TextView invitePassword = (TextView)inviteDialog.findViewById(R.id.invite_password);
        String invite_password = invitePassword.getText().toString();
        TextView confirmPassword = (TextView)inviteDialog.findViewById(R.id.invite_confirm_password);
        String confirm_password = confirmPassword.getText().toString();
        if(!invite_password.equals(confirm_password)){
            ToastUtils.show(MainActivity.this,"密码与确认密码不匹配");
            return;

        }


        //加载网络数据
        post()
                .url(Friend_URL)
                .addParams("nick", invite_name)
                .addParams("userName",invite_phone)
                .addParams("password",invite_password)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<FriendModel>(FriendModel.class) {
                    @Override
                    public void onResponse(final FriendModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            //ToastUtils.show(MainActivity.this,response.getMessage());
                            inviteDialog.hide();
                            onMessageDialogClick(response.getMessage());
                            return;
                        }
                        //显示对话框
                        inviteDialog.hide();
                        onMessageDialogClick(response.getMessage());

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });

    }

    public void onMessageDialogClick(String text){
        if(messageDialog==null){
            messageDialog =  new Dialog(MainActivity.this);
            messageDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            messageDialog.setContentView(R.layout.dialog_message);
            // inviteDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            messageDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            messageDialog.setCancelable(false);
            ((TextView)messageDialog.findViewById(R.id.message_txt)).setText(text);

        }else{
            ((TextView)messageDialog.findViewById(R.id.message_txt)).setText(text);

        }

        messageDialog.show();

    }

    public static void _onMessageDialogClick(String text,MainActivity _this){
        _this.dealDialog.hide();
       _this.onMessageDialogClick(text);

    }



    public void onMessageClose(View view){
        messageDialog.hide();
    }


    public void onMyFriendListClick(View view){
        if(friendDialog==null){
            friendDialog =  new Dialog(MainActivity.this);
            friendDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            friendDialog.setContentView(R.layout.dialog_friend_second);
            // inviteDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            friendDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            friendDialog.setCancelable(false);
            friendAdapter = new FriendAdapter(MainActivity.this);
            friendAdapter.setmData(new ArrayList<FriendItem>());
             ListView friendList =  (ListView)friendDialog.findViewById(R.id.friend_list);
            friendList.setAdapter(friendAdapter);
            //getMyFriendList(friendListPageNum.toString(),friendListPageSize.toString());
            getMyFriendList("0",friendListPageSize.toString());

        }

        friendDialog.show();
    }
    /*
    好友下一页
    * */
    public void onMyFriendListPageNext(View view){
       // Integer last = (int)Math.ceil(friendListTotal/friendListPageSize);
        int last = friendListTotal%friendListPageSize==0? friendListTotal/friendListPageSize : (friendListTotal/friendListPageSize)+1;
        if(friendListPageNum>=last){
            ToastUtils.show(MainActivity.this,"已经是最后一页");
            return;
        }
        friendListPageNum++;
        Integer offset = (friendListPageNum-1)*friendListPageSize;
        getMyFriendList(offset.toString(),friendListPageSize.toString());

    }
    /*
   好友上一页
   * */
    public void onMyFriendListPageLast(View view){
        if(friendListPageNum.equals(1)){
                ToastUtils.show(MainActivity.this,"已经是第一页");
                return;
            }
        friendListPageNum--;
        Integer offset = (friendListPageNum-1)*friendListPageSize;


        getMyFriendList(offset.toString(),friendListPageSize.toString());

    }

    public void setMyFriendListTotal(Integer total){
        friendListTotal = total;
        ((TextView)friendDialog.findViewById(R.id.friend_list_amount)).setText(friendListTotal.toString());

    }

    public void onMyFriendActiveClick(View view){
        friendDialog.hide();
        if(friendActiveDialog==null){
            friendActiveDialog =  new Dialog(MainActivity.this);
            friendActiveDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            friendActiveDialog.setContentView(R.layout.dialog_friend);
            // inviteDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            friendActiveDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            friendActiveDialog.setCancelable(false);

        }

        friendActiveDialog.show();

    }


    public void getMyFriendList(String start,String limit){

        //加载网络数据
        post()
                .url(Friend_LIST_URL)
                .addParams("start", start)
                .addParams("limit",limit)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<FriendListModel>(FriendListModel.class) {
                    @Override
                    public void onResponse(final FriendListModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                              return;
                        }
                        friendAdapter.setmData(response.getList());
                        friendAdapter.notifyDataSetChanged();
                        setMyFriendListTotal(response.getTotalCount());

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });
    }

    /*
    * 搜索好友激活
    * */
    public void onFriendSearchClick(View view){
        EditText inputPhone = (EditText) friendActiveDialog.findViewById(R.id.friend_input_phone);
        String phone = inputPhone.getText().toString();
        //加载网络数据
        OkHttpUtils
               .post()
                .url(Friend_SEARCH_URL)
                .addParams("userName", phone)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<FriendSearchModel>(FriendSearchModel.class) {
                    @Override
                    public void onResponse(final FriendSearchModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                            return;
                        }
                        ((TextView)friendActiveDialog.findViewById(R.id.friend_input_username)).setText(response.getNickName());
                        ((TextView)friendActiveDialog.findViewById(R.id.friend_phone)).setText(response.getUserName());
                        ((TextView)friendActiveDialog.findViewById(R.id.friend_invitor)).setText(response.getFatherID());



                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });

    }

    public void onFriendActiveBtnClick(View view){
        EditText inputPhone = (EditText) friendActiveDialog.findViewById(R.id.friend_input_phone);
        String phone = inputPhone.getText().toString();
        //加载网络数据
        OkHttpUtils
                .post()
                .url(Friend_ACTIVE_URL)
                .addParams("toUserName", phone)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<ActiveModel>(ActiveModel.class) {
                    @Override
                    public void onResponse(final ActiveModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            //ToastUtils.show(MainActivity.this,response.getMessage());
                            //return;
                        }
                        friendActiveDialog.hide();
                        onMessageDialogClick(response.getMessage());


                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });

    }

    /*
    * 增值
    * */
    public void onIncrementClick(View view){
              post()
                    .url(INCREMENT_URL)
                    .addParams("token", CommonUtils.getToken())
                    .build()
                    .execute(new JsonCallback<IncrementModel>(IncrementModel.class) {
                        @Override
                        public void onResponse(final IncrementModel response,int id) {
                            if (response == null) {
                                ToastUtils.show(MainActivity.this,"数据错误");
                                return;
                            }else if(!response.isSuccess()){
                               // ToastUtils.show(MainActivity.this,response.getMessage());
                               // return;
                            }
                             onMessageDialogClick(response.getMessage());
                            //显示对话框
                            getUserInfo(CommonUtils.getToken());
                            //((TextView)incomeDialog.findViewById(R.id.income_txt)).setText(response.getMessage());

                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e("error",e.toString());
                            ToastUtils.show(MainActivity.this,"网络错误");
                            return;
                        }
                    });

    }

    public void onIncrementCloseClick(View view){
        incrementDialog.hide();
    }


    public void intBuildSound(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            AudioAttributes audioAttrib = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_GAME)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();
            mSound = new SoundPool.Builder().setAudioAttributes(audioAttrib).setMaxStreams(6).build();
        }
        else {

            mSound = new SoundPool(6, AudioManager.STREAM_MUSIC, 0);
        }
        soundId =  mSound.load(this, R.raw.build, 1);

    }

    public void playBuildSound(){
//        MediaPlayer mp;
//        mp = new MediaPlayer();
//        // 将音乐保存在res/raw/xingshu.mp3,R.java中自动生成{public static final int xingshu=0x7f040000;}
//        mp = MediaPlayer.create(MainActivity.this, R.raw.build);
//        // 在MediaPlayer取得播放资源与stop()之后要准备PlayBack的状态前一定要使用MediaPlayer.prepeare()
//        try {
//            mp.prepare();
//            mp.start();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        mSound.play(soundId,1,1,2,0,1);
    }

    public void onBuildBuyClick(View view){
        //请求网络
        if(build_tab_selected_item==null){
            ToastUtils.show(MainActivity.this,"请选择建筑物");
            return;
        }

        post()
                .url(HOUSE_URL)
                .addParams("src",build_tab_selected_item.toString())
                .addParams("type",build_tab.toString())
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<IncrementModel>(IncrementModel.class) {
                    @Override
                    public void onResponse(final IncrementModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                           // playBuildSound();
                            onMessageDialogClick(response.getMessage());
                             return;
                        }
                       // playBuildSound();
                        onMessageDialogClick(response.getMessage());
                        addBuild(build_tab_selected_item);
                        playBuildSound();
                        //显示对话框
                        //getUserInfo(CommonUtils.getToken());
                        //((TextView)incomeDialog.findViewById(R.id.income_txt)).setText(response.getMessage());

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });

    }

    public Integer getSelectedItem(int positon){

        if(build_tab.equals(1)){
          return positon+1;
        }else if(build_tab.equals(2)){
            return 5+positon+1;
        }else if(build_tab.equals(3)){
            return 10+positon+1;
        }
        return null;
    }






    /*
   * 经营
   * */
    public void onBusinessClick(View view){
        post()
                .url(BUSINESS_URL)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<BusinessModel>(BusinessModel.class) {
                    @Override
                    public void onResponse(final BusinessModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            // ToastUtils.show(MainActivity.this,response.getMessage());
                            // return;
                        }
                        onMessageDialogClick(response.getMessage());
                        //显示对话框
                        getUserInfo(CommonUtils.getToken());
                        //((TextView)incomeDialog.findViewById(R.id.income_txt)).setText(response.getMessage());

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });

    }


    public void onDealClick(View view){

        if(dealDialog==null){
            dealDialog =  new Dialog(MainActivity.this);
            dealDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            dealDialog.setContentView(R.layout.dialog_deal);
            // inviteDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            dealDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            dealDialog.setCancelable(false);

            transListPageNum = 1;
            dealAdapter = new DealAdapter(MainActivity.this);
            ListView dealList =  (ListView)dealDialog.findViewById(R.id.deal_list);
            dealList.setAdapter(dealAdapter);
            getTransList("0",transListPageSize.toString());
            getNewsList("0","4");
            List<ReportItem> reportList = new ArrayList<ReportItem>();
            ReportItem reportItem = new ReportItem();
            reportItem.setDescription("如出现违规会员交易被骗，请联系客服QQ：1833253951 进行举报投诉");
            reportList.add(reportItem);
            dealAdapter.setReportList(reportList);





        }
         dealDialog.show();


    }

    public void onDealTabClick(View view){

        switch (view.getId()){
            case R.id.tab_record:
                dealAdapter.setCurrentTab(dealAdapter.TAB_RECORD);
                dealAdapter.notifyDataSetChanged();
                break;

            case R.id.tab_news:
                dealAdapter.setCurrentTab(dealAdapter.TAB_NEWS);

                dealAdapter.notifyDataSetChanged();

                break;
            case R.id.tab_report:
                dealAdapter.setCurrentTab(dealAdapter.TAB_REPORT);
                dealAdapter.notifyDataSetChanged();
                break;



        }
    }



    public void onDealLastPageCLick(View view){
        if(dealAdapter.getCurrentTab().equals(dealAdapter.TAB_NEWS)||dealAdapter.getCurrentTab().equals(dealAdapter.TAB_REPORT)){
            return;
        }
        if(transListPageNum.equals(1)){
            ToastUtils.show(MainActivity.this,"已经是第一页");
            return;
        }
        transListPageNum--;
        Integer offset = (transListPageNum-1)*transListPageSize;



        getTransList(offset.toString(),transListPageSize.toString());



    }

    public void onDealNextPageCLick(View view){
        if(dealAdapter.getCurrentTab().equals(dealAdapter.TAB_NEWS)||dealAdapter.getCurrentTab().equals(dealAdapter.TAB_REPORT)){
            return;
        }
     //   Integer last = (int)Math.ceil(transListTotal/transListPageSize);
        int last = transListTotal%transListPageSize==0? transListTotal/transListPageSize : (transListTotal/transListPageSize)+1;
        if(transListPageNum>=last){
            ToastUtils.show(MainActivity.this,"已经是最后一页");
            return;
        }
        transListPageNum++;
        Integer offset = (transListPageNum-1)*transListPageSize;

        getTransList(offset.toString(),transListPageSize.toString());

    }

    public void refreshDealPage(int pageNum){
        Integer offset = (pageNum-1)*transListPageSize;

        getTransList(offset.toString(),transListPageSize.toString());
    }

    /*
    * 获取交易列表
    * */
    public void getTransList(String start,String limit){
        //加载网络数据
        post()
                .url(TRANS_URL)
                .addParams("start", start)
                .addParams("page",limit)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<DealListModel>(DealListModel.class) {
                    @Override
                    public void onResponse(final DealListModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                            return;
                        }
                        transListTotal = response.getTotalCount();
                        dealAdapter.setDealList(response.getList());
                        if(dealAdapter.getCurrentTab().equals(dealAdapter.TAB_RECORD)){
                                  dealAdapter.notifyDataSetChanged();

                        }




                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });
    }

    /*
    * 获取新闻接口
    * */
    public void getNewsList(String start,String limit){
        //加载网络数据
        post()
                .url(NEWS_URL)
                .addParams("start", start)
                .addParams("limit",limit)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<NewsListModel>(NewsListModel.class) {
                    @Override
                    public void onResponse(final NewsListModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                            return;
                        }
                        dealAdapter.setNewsList(response.getList());

                        if(dealAdapter.getCurrentTab().equals(dealAdapter.TAB_NEWS)){

                                 dealAdapter.notifyDataSetChanged();


                        }




                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });
    }



  public void jumpToDealSearch(View view){
      dealDialog.hide();
      if(dealSearchDialog==null){
          dealSearchDialog =  new Dialog(MainActivity.this);
          dealSearchDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

          dealSearchDialog.setContentView(R.layout.dialog_deal_search);
        // dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
          dealSearchDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
          dealSearchDialog.setCancelable(false);
      }


      dealSearchDialog.show();


  }

    /*
   * 交易搜索
   * */
    public void onDealSearchClick(View view){
        EditText inputPhone = (EditText) dealSearchDialog.findViewById(R.id.deal_input_phone);
        String phone = inputPhone.getText().toString();
        //加载网络数据
        OkHttpUtils
                .post()
                .url(Friend_SEARCH_URL)
                .addParams("userName", phone)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<FriendSearchModel>(FriendSearchModel.class) {
                    @Override
                    public void onResponse(final FriendSearchModel response,int id) {
                        dealUser = response;
                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                            return;
                        }

                        ((TextView)dealSearchDialog.findViewById(R.id.deal_input_username)).setText(response.getNickName());
                        ((TextView)dealSearchDialog.findViewById(R.id.deal_phone)).setText(response.getUserName());
                        ((TextView)dealSearchDialog.findViewById(R.id.deal_invitor)).setText(response.getFatherID());



                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });

    }
    public void onDealBtnClick(View view){
        if(dealUser!=null && !dealUser.getUserName().isEmpty()){
            TextView inputPhone = (TextView) dealSearchDialog.findViewById(R.id.deal_phone);
            String phone = inputPhone.getText().toString();
            EditText inputAmount = (EditText) dealSearchDialog.findViewById(R.id.deal_input_amount);
            String amount = inputAmount.getText().toString();

            sendSms(phone,amount);

        }else{
            ToastUtils.show(MainActivity.this,"请指定用户交易");

        }
    }

    public void JumpToDealCode(){
        dealSearchDialog.hide();
        if(dealCodeDialog==null){
            dealCodeDialog =  new Dialog(MainActivity.this);
            dealCodeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dealCodeDialog.setContentView(R.layout.dialog_deal_code);
            // dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            dealCodeDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            dealCodeDialog.setCancelable(false);
        }


        dealCodeDialog.show();

    }
    public void onDialogClose(View view){
        switch (view.getId()){
            case R.id.deal_code_close:
                dealCodeDialog.hide();
                break;
            case R.id.deal_search_close:
                dealSearchDialog.hide();
                break;
            case R.id.deal_close:
                dealDialog.dismiss();
                dealDialog = null;
                break;
            case R.id.setting_close:
                settingDialog.hide();
                break;
            case R.id.invite_close:
                inviteDialog.hide();
                break;
            case R.id.friend_close:
                friendActiveDialog.hide();
                break;
            case R.id.friend_second_close:
                friendDialog.hide();
                break;
            case R.id.password_close:
                changePasswordDialog.hide();
                break;
            case R.id.build_close:
                buildDialog.hide();
                break;

        }
    }


    public void onDealSendTranClick(View view){

        EditText inputCode = (EditText) dealCodeDialog.findViewById(R.id.deal_input_code);
        String code = inputCode.getText().toString();

        TextView inputPhone = (TextView) dealSearchDialog.findViewById(R.id.deal_phone);
        String phone = inputPhone.getText().toString();
        EditText inputAmount = (EditText) dealSearchDialog.findViewById(R.id.deal_input_amount);
        String amount = inputAmount.getText().toString();

        //加载网络数据
        OkHttpUtils
                .post()
                .url(SEND_TRANS_URL)
                .addParams("code", code)
                .addParams("userName", phone)
                .addParams("money", amount)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<FriendSearchModel>(FriendSearchModel.class) {
                    @Override
                    public void onResponse(final FriendSearchModel response,int id) {

                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            //ToastUtils.show(MainActivity.this,response.getMessage());
                            //return;
                        }
                        dealCodeDialog.hide();
                        onMessageDialogClick(response.getMessage());

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });




    }


    public static void agreeDeal(DealItem item){
        //加载网络数据
        OkHttpUtils
                .post()
                .url(AGREE_URL)
                .addParams("id",item.getId().toString())
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<SmsModel>(SmsModel.class) {
                    @Override
                    public void onResponse(final SmsModel response,int id) {

                        if (response == null) {
                            ToastUtils.show(_this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            // ToastUtils.show(_this,response.getMessage());
                            // return;
                        }

                        _onMessageDialogClick(response.getMessage(),_this);
                        _this.refreshDealPage(_this.transListPageNum);



                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(_this,"网络错误");
                        return;
                    }
                });
    }

    public static void refuseDeal(DealItem item){
        //加载网络数据
        OkHttpUtils
                .post()
                .url(REFUSE_URL)
                .addParams("id",item.getId().toString())
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<SmsModel>(SmsModel.class) {
                    @Override
                    public void onResponse(final SmsModel response,int id) {

                        if (response == null) {
                            ToastUtils.show(_this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            // ToastUtils.show(_this,response.getMessage());
                            // return;
                        }

                        _onMessageDialogClick(response.getMessage(),_this);
                        _this.refreshDealPage(_this.transListPageNum);



                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(_this,"网络错误");
                        return;
                    }
                });

    }



    public static void finishDeal(DealItem item){
        //加载网络数据
        OkHttpUtils
                .post()
                .url(FINFISH_URL)
                .addParams("id",item.getId().toString())
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<SmsModel>(SmsModel.class) {
                    @Override
                    public void onResponse(final SmsModel response,int id) {

                        if (response == null) {
                            ToastUtils.show(_this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            // ToastUtils.show(_this,response.getMessage());
                            // return;
                        }

                        _onMessageDialogClick(response.getMessage(),_this);
                        _this.refreshDealPage(_this.transListPageNum);



                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(_this,"网络错误");
                        return;
                    }
                });

    }


    public void sendSms(String phone,String payNum){
        //加载网络数据
        OkHttpUtils
                .post()
                .url(SMS_URL)
                .addParams("phoneNum", phone)
                .addParams("payNum", payNum)
                .addParams("token", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<SmsModel>(SmsModel.class) {
                    @Override
                    public void onResponse(final SmsModel response,int id) {

                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                            return;
                        }
                        JumpToDealCode();

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });
    }









    public void onLoginClick(View view){
       // Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show();
        Dialog dialog =  new Dialog(MainActivity.this);
        dialog.setContentView(R.layout.dialog_login);

       // dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable());
        dialog.setCancelable(false);
        dialog.show();
    }


   public void onBuildSeniorClick(View view){
       build_tab = 2;
       build_tab_selected_item = null;
       data_list.clear();
       getSeniorData();
       sim_adapter.notifyDataSetChanged();
   }
    public void onBuildJuniorClick(View view){
        build_tab = 1;
        build_tab_selected_item = null;
         data_list.clear();
        getJuniorData();
        sim_adapter.notifyDataSetChanged();
    }

    public void onBuildHighClick(View view){
        build_tab = 3;
        build_tab_selected_item = null;

        data_list.clear();
        getHighData();
        sim_adapter.notifyDataSetChanged();
    }


    public void onBuildClick(View view){
        if(buildDialog==null) {
            buildDialog = new Dialog(this);
            buildDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            buildDialog.setContentView(R.layout.dialog_build);
            buildDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            buildDialog.setCancelable(false);
            gview = (GridView) buildDialog.findViewById(R.id.img_list);
            gview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    build_tab_selected_item = getSelectedItem(position);
                    //ToastUtils.show(MainActivity.this,String.valueOf(id));
                   //view.setBackgroundColor(0x7f040000);
                }
            });

            //新建List
            data_list = new ArrayList<Map<String, Object>>();
            getJuniorData();

            String[] from = {"image"};
            int[] to = {R.id.bulid_image};
            sim_adapter = new SimpleAdapter(this, data_list, R.layout.tab_item_view, from, to);
            //配置适配器
            gview.setAdapter(sim_adapter);

        }

        buildDialog.show();



    }
    public List<Map<String, Object>> getHighData(){
        //cion和iconName的长度是相同的，这里任选其一都可以
        int[] icon = {R.drawable.build_high_1 ,R.drawable.build_high_2,R.drawable.build_high_3};

        for(int i=0;i<icon.length;i++){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);

            data_list.add(map);
        }

        return data_list;
    }




    public List<Map<String, Object>> getSeniorData(){
        //cion和iconName的长度是相同的，这里任选其一都可以

        int[] icon = {R.drawable.build_senior_1,R.drawable.build_senior_2,R.drawable.build_senior_3,R.drawable.build_senior_4,
                R.drawable.build_senior_5};

        for(int i=0;i<icon.length;i++){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);

            data_list.add(map);
        }

        return data_list;
    }


    public List<Map<String, Object>> getJuniorData(){
        //cion和iconName的长度是相同的，这里任选其一都可以
        int[] icon = {R.drawable.build_junior_1 ,R.drawable.build_junior_2,R.drawable.build_junior_3,R.drawable.build_junior_4,
                R.drawable.build_junior_5};

        for(int i=0;i<icon.length;i++){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);

            data_list.add(map);
        }

        return data_list;
    }



    public void onSettingClick(View view){
        if(settingDialog==null) {
            settingDialog = new Dialog(this);
            settingDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            settingDialog.setContentView(R.layout.dialog_voice);
            settingDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            settingDialog.setCancelable(false);
            final AudioManager audiomanage = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            final SeekBar soundBar = (SeekBar) settingDialog.findViewById(R.id.seekbar_sound);
            final int maxVolume;
            currentVolume = audiomanage.getStreamVolume(AudioManager.STREAM_MUSIC);  //获取当前值
            soundBar.setProgress(currentVolume);

            maxVolume = audiomanage.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            soundBar.setMax(maxVolume);   //拖动条最高值与系统最大声匹配
            //绑定声音
            soundBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() //调音监听器
            {
                public void onProgressChanged(SeekBar arg0, int progress, boolean fromUser) {
                    audiomanage.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                    currentVolume = audiomanage.getStreamVolume(AudioManager.STREAM_MUSIC);  //获取当前值
                    soundBar.setProgress(currentVolume);

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub


                }


            });
        }

        settingDialog.show();
    }

    public void onChangePasswordClick(View view){
        settingDialog.hide();
        if(changePasswordDialog==null){
            changePasswordDialog = new Dialog(this);
            changePasswordDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            changePasswordDialog.setContentView(R.layout.dialog_password);
            changePasswordDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            changePasswordDialog.setCancelable(false);

        }
        changePasswordDialog.show();
    }


    public void onChangePasswordSubmitClick(View view ){
        //获取密码信息
        EditText inputOld = (EditText) changePasswordDialog.findViewById(R.id.password_old);
        EditText inputNew = (EditText) changePasswordDialog.findViewById(R.id.password_new);
        EditText inputNewConfirm = (EditText) changePasswordDialog.findViewById(R.id.password_confirm);
        String oldPwd = inputOld.getText().toString();
        String newPwd = inputNew.getText().toString();
        String newPwdConfirm = inputNewConfirm.getText().toString();
        if(newPwd.isEmpty()){
            ToastUtils.show(MainActivity.this,"新密码不能为空");
            return;
        }
        if(!newPwd.equals(newPwdConfirm)){
            ToastUtils.show(MainActivity.this,"新密码与确认密码不匹配");
            return;
        }

        OkHttpUtils
                .post()
                .url(CHANGE_PASSWORD_URL)
                .addParams("newPassword", newPwd)
                .addParams("password", oldPwd)
                .addParams("userId", CommonUtils.getToken())
                .build()
                .execute(new JsonCallback<SmsModel>(SmsModel.class) {
                    @Override
                    public void onResponse(final SmsModel response,int id) {

                        if (response == null) {
                            ToastUtils.show(MainActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(MainActivity.this,response.getMessage());
                            return;
                        }
                        ToastUtils.show(MainActivity.this,response.getMessage());
                        changePasswordDialog.hide();

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(MainActivity.this,"网络错误");
                        return;
                    }
                });






    }

    /*
    * 退出登录
    * */
    public void onLogoutClick(View view){
        SharedPreferences sp = getSharedPreferences("userInfo", 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("token","");
        editor.commit();
        Intent i = new Intent();
        i.setClass(MainActivity.this, LoginActivity.class);
        startActivity(i);
        this.finish();

    }


    public void startCloudAnimation(){
        final ImageView up_cloud = (ImageView)findViewById(R.id.up_cloud);
        final ImageView down_cloud = (ImageView)findViewById(R.id.down_cloud);
        final Animation upAnimation = AnimationUtils.loadAnimation(this,R.anim.up_cloud_right_to_left);
       final Animation upLeftAnimation = AnimationUtils.loadAnimation(this,R.anim.up_cloud_left_to_right);
        final Animation downAnimation = AnimationUtils.loadAnimation(this,R.anim.down_cloud_right_to_left);
        final Animation downLeftAnimation = AnimationUtils.loadAnimation(this,R.anim.down_cloud_left_to_right);

        upAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //animation.start();
                up_cloud.startAnimation(upLeftAnimation);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        upLeftAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                up_cloud.startAnimation(upAnimation);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        downAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
               down_cloud.startAnimation(downLeftAnimation);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        downLeftAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                down_cloud.startAnimation(downAnimation);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        up_cloud.startAnimation(upAnimation);
        down_cloud.startAnimation(downAnimation);

    }

    public void startAnimation(){
        //第一个动画
        RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.activity_main);

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int height = metric.heightPixels;
        RelativeLayout.LayoutParams  uplp,lowlp;

        ImageView bigWater = new ImageView(this);
        uplp =   new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        uplp.leftMargin = (int) (width * 0.57);
        uplp.topMargin = (int) (height * 0.3);
        bigWater.setLayoutParams(uplp);
        bigWater.setBackgroundResource(R.drawable.animation_list);
        AnimationDrawable animaition = (AnimationDrawable)bigWater.getBackground();
        animaition.setOneShot(false);
        animaition.start();

        //第二个动画
        ImageView smallWater = new ImageView(this);
        lowlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        lowlp.leftMargin = (int)(width*0.58); //600 300   1440 900
        lowlp.topMargin = (int)(height*0.43);
        smallWater.setLayoutParams(lowlp);
        smallWater.setBackgroundResource(R.drawable.small_animation_list);
        AnimationDrawable animaition2 = (AnimationDrawable)smallWater.getBackground();
        animaition2.setOneShot(false);
        animaition2.start();


        //人动画
        UserModel user = CommonUtils.getCurrentUser();
       // user.setFatherNum(6);
        if(user.getFatherNum()>=1) {
            RelativeLayout.LayoutParams firstlp;
            ImageView firstPeople = new ImageView(this);

            firstlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            firstlp.width = 100;
            firstlp.height = 75;

            firstlp.leftMargin = (int) (width * 0.271); //600 300   1440 900 0.706 0.358
            firstlp.topMargin = (int) (height * 0.172);
            firstPeople.setLayoutParams(firstlp);
            firstPeople.setBackgroundResource(R.drawable.people_1_list);
            AnimationDrawable animaition3 = (AnimationDrawable) firstPeople.getBackground();
            animaition3.setOneShot(false);
            animaition3.start();
            mainLayout.addView(firstPeople);
        }
        if(user.getFatherNum()>=2) {

            RelativeLayout.LayoutParams secondlp;
            ImageView secondPeople = new ImageView(this);

            secondlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            secondlp.width = 100;
            secondlp.height = 75;
            secondlp.leftMargin = (int) (width * 0.133); //600 300   1440 900 0.706 0.358
            secondlp.topMargin = (int) (height * 0.406);
            secondPeople.setLayoutParams(secondlp);
            secondPeople.setBackgroundResource(R.drawable.people_2_list);
            AnimationDrawable animaition4 = (AnimationDrawable) secondPeople.getBackground();
            animaition4.setOneShot(false);
            animaition4.start();
            mainLayout.addView(secondPeople);
        }
        if(user.getFatherNum()>=3) {
            RelativeLayout.LayoutParams thirdlp;
            ImageView thirdPeople = new ImageView(this);

            thirdlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            thirdlp.width = 100;
            thirdlp.height = 75;
            thirdlp.leftMargin = (int) (width * 0.732); //600 300   1440 900 0.706 0.358
            thirdlp.topMargin = (int) (height * 0.308);
            thirdPeople.setLayoutParams(thirdlp);
            thirdPeople.setBackgroundResource(R.drawable.people_3_list);
            AnimationDrawable animaition5 = (AnimationDrawable) thirdPeople.getBackground();
            animaition5.setOneShot(false);
            animaition5.start();
            mainLayout.addView(thirdPeople);
        }
        if(user.getFatherNum()>=4) {
            RelativeLayout.LayoutParams fourlp;
            ImageView fourPeople = new ImageView(this);

            fourlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            fourlp.width = 100;
            fourlp.height = 75;
            fourlp.leftMargin = (int) (width * 0.772); //600 300   1440 900 0.706 0.358
            fourlp.topMargin = (int) (height * 0.521);
            fourPeople.setLayoutParams(fourlp);
            fourPeople.setBackgroundResource(R.drawable.people_4_list);
            AnimationDrawable animaition6 = (AnimationDrawable) fourPeople.getBackground();
            animaition6.setOneShot(false);
            animaition6.start();
            mainLayout.addView(fourPeople);
        }

        if(user.getFatherNum()>=5){
            RelativeLayout.LayoutParams fivelp;
            ImageView fivePeople = new ImageView(this);
            fivePeople.setImageResource(R.drawable.five_frame_001);
            fivelp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            fivelp.width = 100;
            fivelp.height = 75;
            fivelp.leftMargin = (int) (width * 0.226); //600 300   1440 900 0.706 0.358
            fivelp.topMargin = (int) (height * 0.514);
            fivePeople.setLayoutParams(fivelp);
            mainLayout.addView(fivePeople);

        }
        if(user.getFatherNum()>=6){
            RelativeLayout.LayoutParams sixlp;
            ImageView fivePeople = new ImageView(this);
            fivePeople.setImageResource(R.drawable.six_frame_00001);
            sixlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            sixlp.width = 100;
            sixlp.height = 75;
            sixlp.leftMargin = (int) (width * 0.815); //600 300   1440 900 0.706 0.358
            sixlp.topMargin = (int) (height * 0.086);
            fivePeople.setLayoutParams(sixlp);
            mainLayout.addView(fivePeople);

        }


        mainLayout.addView(bigWater);
        mainLayout.addView(smallWater);




    }

    @Override
    protected void onPause() {
        super.onPause();
        stopService(musicService);

    }

    @Override
    protected void onResume() {
        super.onResume();
        startService(musicService);
    }
}
